$(function () {
//声明变量
    //采购订单表格
    var orderBill_dialog =$("#orderBill_dialog");
    //采购订单弹出框
    var orderBill_datagrid = $("#orderBill_datagrid");
    //采购订单弹出表单
    var orderBill_form = $("#orderBill_form");
    //选择商品的数据表格
    var pro_datagrid = $("#pro_datagrid");

    //采购订单列表
    orderBill_datagrid.datagrid({
        url:'/orderBill/query.do',
        fit:true,
        fitColumns:true,
        pagination:true,
        toolbar:'#orderBill_toolbar',
        singleSelect:true,
        columns:[[
            {field:'id',checkbox:true},
            {field:'sn',title:'订单编号',width:100},
            {field:'supplier',title:'供应商',width:100,formatter:function (value,row,index) {
                    return value? value.name:'';
                }},
            {field:'totalNumber',title:'采购总数量',width:100},
            {field:'totalAmount',title:'采购总金额',width:100},
            {field:'inputTime',title:'录入时间',width:100,sortable:true},
            {field:'inputUser',title:'录入人员',width:100,formatter:function (value,row,index) {
                    //当前对象是否存在
                    return value? value.username:'';
                }},
            {field:'auditTime',title:'审核时间',width:100,sortable:true},
            {field:'auditor',title:'审核人员',width:100,formatter:function (value,row,index) {
                    //当前对象是否存在
                    return value? value.username:'';
                }},
            {field:'status',title:'单据状态',width:60,formatter:function (value,row,index) {
                    //判断当前值是true false
                    return value == 2 ? "<font color='green'>已审核</font>" : "<font color='red'>未审核</font>";
                }},
            {field:'depot',title:'入库仓库',width:100,formatter:function (value,row,index) {
                    return value? value.name:'';
                }}
        ]],

        //在数据加载成功的时候触发添加商品明细的按钮
        onLoadSuccess:function () {
            $(".easyui-linkbutton").linkbutton({
            });
        },
        onDblClickRow:function () {
            orderBill_dialog.dialog("setTitle","查看详情");
            methodObj['edit']();
        }
    });

    //配置dialog,form表单
    orderBill_dialog.dialog({
        width:1000,
        height:450,
        buttons:'#form_btn',
        close:true
    });

    $("#product_view").dialog({
        width: 1000,
        height: 450,
        closed: true,
        modal: true,
        title: '添加商品'
    })


    var methodObj = {
        add:function(){
            //清空表单数据
            orderBill_form.form('clear');
            $("#edit_tbody").html("");

            orderBill_dialog.dialog('open');
            orderBill_dialog.dialog('setTitle','新增订单');
        },
        del:function () {
            //获取一行数据
            var row = orderBill_datagrid.datagrid('getSelected');
            //判断是否有选择选择数据
            if (!row) {
                //没有选择数据提示用户
                $.messager.alert("温馨提示", "至少要选择一条数据", "warning");
                return;//终止操作
            }
            //弹出确认框
            $.messager.confirm('确认', '您确认想要执行操作吗？', function (r) {
                if (r) {
                    //给后台发送后台
                    $.get("/orderBill/delete.do", {id: row.id}, function (data) {
                        if (data.success) {
                            $.messager.alert('温馨提示', '操作成功', 'info', function () {
                                //加载刷新到当前界面
                                orderBill_datagrid.datagrid('reload');
                            })
                        } else {
                            $.messager.alert("温馨提示", "操作失败", "error");
                        }
                    })
                }
            })
        },
        edit:function (){
            //获取一行数据
            var row = orderBill_datagrid.datagrid('getSelected');
            //判断是否有选择选择数据
            if (!row) {
                //没有选择数据提示用户
                $.messager.alert("温馨提示","至少要选择一条数据","warning");
                return;//终止操作
            }

            //清空表单数据
            orderBill_form.form('clear');
            $("#edit_tbody").html("");

            //回显供应商
            if(row.supplier){
                row["supplier.id"] = row.supplier.id;
            }
            //回显仓库
            if(row.depot){
                row["depot.id"] = row.depot.id;
            }
            //回显表单
            orderBill_form.form('load',row);

            $.each(row.items, function (index,item) {
                var tr = $("#itemTr tr:first").clone();
                if(row.status == 2){
                    //如果订单状态是已审核状态 设置为只读
                    $(":input").prop("readOnly",true);
                    orderBill_dialog.dialog("setValue","查看明细");
                }else{
                    $(":input").prop("readOnly",false);
                }
                tr.appendTo("#edit_tbody");
                tr.find("[tag=sn]").html(item.product.sn);
                tr.find("[tag=name]").html(item.product.name);
                tr.find("[tag=pid]").val(item.product.id);
                tr.find("[tag=costPrice]").val(item.costPrice);
                tr.find("[tag=amount]").html(item.amount);
                tr.find("[tag=remark]").val(item.remark);
                tr.find("[tag=number]").val(item.number);
                $("#product_view").dialog("close");
            })
            //处理好回显数据后,打开编辑框
            orderBill_dialog.dialog('open');
            //设置标题
            orderBill_dialog.dialog('setTitle','编辑采购订单');
        },
        saved:function (){
            $.each($("#edit_tbody tr"), function (index, item) {
                $(item).find("[tag=pid]").prop("name","items["+index+"].product.id");
                $(item).find("[tag=costPrice]").prop("name","items["+index+"].costPrice");
                $(item).find("[tag=number]").prop("name","items["+index+"].number");
                $(item).find("[tag=remark]").prop("name","items["+index+"].remark");
            });
            //提交表单
            orderBill_form.form("submit",{
                url:'/orderBill/saveOrUpdate.do',

                success:function (data) {
                    //回调函数:data表示返回数据解析为json
                    data = $.parseJSON(data);
                    if (data.success) {
                        //如果返回结果成功__弹出窗口提示
                        $.messager.alert('温馨提示','保存成功','info',function () {
                            orderBill_datagrid.datagrid('reload');
                            methodObj.cancel();
                        })
                    }else {
                        //如果保存失败,则弹出窗口提示
                        $.messager.alert('温馨提示','保存失败','error');
                    }
                }
            });
        },

        changeAudit:function () {
            //判断是否有选中数据
            var row = orderBill_datagrid.datagrid("getSelected");
            if (!row) {
                $.messager.alert('温馨提示', '请选中一条数据!', 'warning');
                return;
            }
            //弹出确认框
            $.messager.confirm('温馨提示', '您想要执行该操作吗?', function (y) {
                if (y) {
                    $.get("/orderBill/audit.do", {id: row.id}, function (data) {
                        if (data.success) {
                            $.messager.alert('温馨提示', "审核成功", 'info', function () {
                                orderBill_datagrid.datagrid("reload");
                            });
                        } else {
                            $.messager.alert('温馨提示', "操作失败", 'error');
                        }
                    }, "json")
                }
            });
        },

        cancel: function (){
            //关闭弹出框:
            orderBill_dialog.dialog('close');
        },

        //刷新按钮
        refresh:function () {
            //刷新页面
            orderBill_datagrid.datagrid('reload');
        },

        addProduct: function () {
            $("#product_view").dialog("open");
        }

    };

    //统一绑定事件:
    $("a[data-cmd]").click(function () {
        var methodname = $(this).data("cmd");
        //动态获取调用方法名字,调用方法;
        methodObj[methodname]();
    })

    pro_datagrid.datagrid({
        url:'/product/query.do',
        fit: true,
        fitColumns: true,
        singleSelect: true,
        rownumbers: true,
        toolbar: '#view_toolbar',
        columns:[[
            {field: 'name', title: '商品名', width: 100},
            {field:'classify',title:'一级类别',width:80,formatter:function (value,row,index) {

                    //当前对象是否存在
                    return row? row.classify.classname:'';
                }},
            {field:'classifyChild',title:'二级类别',width:80,formatter:function (value,row,index) {
                    //当前对象是否存在
                    return row? row.classifyChild.linkName:'';
                }},
            {field: 'sn', title: '商品编码', width: 100},
            {field: 'salePrice', title: '零售价', width: 100}
        ]],
        onClickRow: function (index, row) {
            var copy = $("#itemTr tr:first").clone();
            copy.appendTo("#edit_tbody");
            copy.find("[tag=sn]").html(row.sn);
            copy.find("[tag=name]").html(row.name);
            copy.find("[tag=pid]").val(row.id);
            copy.find("[tag=costPrice]").val(row.costPrice);
            $("#product_view").dialog("close");
        },
        detailFormatter: function (rowIndex, rowData) {
            return "<table><tr><td width='200'>商品编码: " + rowData.sn + "</td>"+
                "<td width='200'>商品名称: " + rowData.name + "</td>"+
                "<td width='200'>商品售价: " + rowData.salePrice + "</td>"+
                "<td width='200'>会员折扣价: " + rowData.countPrice + "</td>"+
                "<td width='200'>商品简介: " + rowData.remark + "</td>"+
                "</tr></table>";
        }
    })
    $("#edit_tbody").on("change", "[tag=costPrice],[tag=number]", function () {
        var currentTr = $(this).closest('tr');
        var price = currentTr.find("[tag=costPrice]").val() || 0;
        var number = currentTr.find("[tag=number]").val() || 0;
        currentTr.find("[tag=amount]").html((price * number).toFixed(2));
    }).on("click", ".deleteItem", function () {
        var currentTr = $(this).closest("tr");
        currentTr.remove();
    })

});

//删除

//编辑

//============表单的 按钮 保存/取消=================


//保存密码


//高级查询


//修改密码

